import path from 'path';
import axios from 'axios';
import { NFTStorage } from 'nft.storage';
import { filesFromPaths } from 'files-from-path';

// NFT.Storage API Token
const token =
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkaWQ6ZXRocjoweDI2RmRFNERDYTM1MjY0QWNhOUYzMWYwNjBDMGQyMWIwNUU2RDA3RDgiLCJpc3MiOiJuZnQtc3RvcmFnZSIsImlhdCI6MTY4Mzc5MjQ0Nzg1MSwibmFtZSI6Illhbmd4In0.1p9rmfQko4_xGH3StFEjSBIfyka1_tn0guoo60GQmaQ';
// cloudflare 区域 ID
const zone_identifier = '1e04741cbfec02f8ca79642285d720c5';
// cloudflare API令牌
const authorization = 'Bearer mt2VFv0uY0C7SjjWgcdVPdIj1LOPBNao66gyOiVT';
// 配置网关
const domainList = [
  { env: 'main', id: 'ad955c12229d4b5b8fca12cc8f2c3607', name: 'axie-1game.vip' },
  { env: 'test', id: 'c08cf9d686704f10a2780f14feb8309d', name: 'test.axie-1game.vip' }
];

async function uploadDirectory() {
  try {
    const env = process.argv[2];
    const directoryPath = './dist';

    const files = await filesFromPaths([directoryPath], {
      recursive: true,
      pathPrefix: path.resolve(directoryPath),
      hidden: true
    });

    console.log('开始上传：', directoryPath);
    const storage = new NFTStorage({ token });
    const cid = await storage.storeDirectory(files);
    console.log('上传成功！', cid);

    for (const [index, element] of domainList.entries()) {
      if (element.env == env) {
        await new Promise((resolve) => setTimeout(resolve, 500)); // 500ms delay
        console.log('开始部署：', element.name);
        try {
          const response = await axios.patch(
            `https://api.cloudflare.com/client/v4/zones/${zone_identifier}/web3/hostnames/${element.id}`,
            { dnslink: `/ipfs/${cid}` },
            { headers: { 'Content-Type': 'application/json', Authorization: authorization } }
          );
          if (response.data.success) {
            console.log('部署成功！', `https://${element.name}`);
          }
        } catch (error) {
          console.log('部署失败！', `https://${element.name}`, error);
        }
      }
    }
  } catch (error) {
    console.error(error);
  }
}

uploadDirectory();

// npm start
// npm run start:prod
// npm run build:dev
// npm run build
